import {Component, Input, OnInit} from '@angular/core';
import {Menu} from '../../entity/menu';
import {DocMenu} from '../../entity/doc-menu';
import {DocIndexService} from '../../service/doc-index.service';
import {MenuService} from '../../service/menu.service';
import {UserService} from '../../service/user.service';
import {MessageService} from '../../service/message.service';
import {AlertMessage} from '../../entity/alert-message';
import {User} from '../../entity/user';

@Component({
    selector: 'app-left-nav-doc-item',
    templateUrl: './left-nav-doc-item.component.html',
    styleUrls: ['./left-nav-doc-item.component.css']
})
export class LeftNavDocItemComponent implements OnInit {
    @Input()
    menuList: Menu[];

    user: User;

    constructor(private menuService: MenuService,
                private messageService: MessageService,
                private userService: UserService,
                private docIndexService: DocIndexService) {
    }

    ngOnInit() {
        this.user = this.userService.getUser();
    }

    setTop(menu: DocMenu) {
        if (menu.top) {
            menu.top = false;
        } else {
            menu.top = true;
        }
        this.docIndexService.setDocFocus(menu);
    }

    expanding(menu: Menu): void {
        this.menuService.expandMenu(menu, this.user);
    }

    /**
     * 成为所有者
     * @param {Menu} menu
     */
    asOwner(menu: Menu) {
        this.userService.asOwner(menu.id).subscribe(result => {
            if (result) {
                menu.owner = true;
                this.messageService.add(<AlertMessage>{
                    id: 'set-owner-' + menu.id,
                    type: 'success',
                    html: `文档${menu.id}所有者设置成功！`,
                    time: 5
                });
            }
        });
    }

    /**
     * 放弃所有者身份
     * @param {Menu} menu
     */
    abandonOwner(menu: Menu) {
        this.userService.removeOwner(menu.id).subscribe(result => {
            if (result) {
                menu.owner = false;
                this.messageService.add(<AlertMessage>{
                    id: 'remove-owner-' + menu.id,
                    type: 'success',
                    html: `放弃文档${menu.id}所有者身份成功！`,
                    time: 5
                });
            }
        });
    }
}
